package com.ncpowernode.utils;


import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;

@Component
public class HttpUtils {

    private PoolingHttpClientConnectionManager cm;

    public HttpUtils(){
        cm = new PoolingHttpClientConnectionManager();
        // 设置最大连接数
        cm.setMaxTotal(100);
        // 设置最大主机的最大连接数
        cm.setDefaultMaxPerRoute(10);
    }

    /**
     * 根据请求地址下载页面数据
     * @param url
     * @return 页面数据
     */
    public String doGetHtml(String url){
        CloseableHttpResponse response = null;
        try {
            CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(this.cm).build();
            // URIBuilder uriBuilder = new URIBuilder(url);
            HttpGet httpGet = new HttpGet(url);
            httpGet.setConfig(getConfig());
            response = httpClient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() >= 200 ||
                    response.getStatusLine().getStatusCode() < 300 &&
                            response.getEntity()!=null) {
                return EntityUtils.toString(response.getEntity(),"utf-8");
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally {
            if(response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return "";
    }

    /**
     * 下载图片
     * @return 图片名称
     */
    public String doGetImage(String url){
        CloseableHttpResponse response = null;
        try {
            CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(this.cm).build();
            // URIBuilder uriBuilder = new URIBuilder(url);
            HttpGet httpGet = new HttpGet(url);
            httpGet.setConfig(getConfig());
            response = httpClient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() >= 200 ||
                    response.getStatusLine().getStatusCode() < 300 &&
                            response.getEntity()!=null) {
                // 下载图片
                // 获取图片的后缀
                String extName = url.substring(url.lastIndexOf("."));
                // 创建图片名，重命名图片
                String picName = UUID.randomUUID().toString() + extName;
                // 下载图片
                // 声明outputStream
                File file = new File("D:\\Study\\Codes\\springboot-crawler\\images\\" + picName);
                OutputStream out = new FileOutputStream(file);
                response.getEntity().writeTo(out);
                // 返回图片名称
                return picName;
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally {
            if(response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return "";
    }

    private RequestConfig getConfig(){
        return RequestConfig.custom()
                .setSocketTimeout(10000)  // 数据传输最长时间
                .setConnectTimeout(1000) // 创建连接的最长时间
                .setConnectionRequestTimeout(500) // 获取连接的最长时间
                .build();
    }

}
